/**
 * 模态框
 */
module.exports = function($scope, transData, $state, $modalInstance, $stateParams, $resource,items,auth){

    var exist_menu = [];    //存放角色已有的菜单

    start();
    
    //初始化查询全部菜单
    function start(){
        $resource('/api/as/sc/menu/getOneList', {}, {}).save({'parent_id': '1'}, function (res) {
            if (res.errcode === 0) {
                $scope.menu_list = res.data;
                $scope.selectMenu($scope.menu_list[0]);
            } else {
                alert(res.errmsg);
            }
        });
    }

    //选择二级菜单
    $scope.selectMenu = function (item) {
        $scope.menuTwo_list = [];
        var para = {'role_id': auth.id, 'parent_id': item.id};
        $resource('/api/ac/sc/roleService/getMenuForRoleList', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                $scope.menuTwo_list = transData(res.data, 'id', 'parent_id', 'children');
            } else {
                alert(res.errmsg);
            }
        });
    }

    //选择菜单权限
    $scope.sel = function (menuTwo,menuThree) {
        var para = {
            'role_id': auth.id, 
            'exist':menuThree.exist, 
            'menu_ids': '',     //同级别菜单id
            'id': menuThree.id, 
            'children': '',     //三级菜单下的接口!!新系统已取消
            'parentId': menuTwo.id,
            'parentOne': menuTwo.parent_id,
            'type': '3'
        };
        if(menuThree.children != undefined){
            for(var i = 0; i < menuThree.children.length; i++){
                para.children += menuThree.children[i].id + ',';
            }
        }
        for(var i = 0; i < menuTwo.children.length; i++){
            para.menu_ids += menuTwo.children[i].id + ',';
        }
        para.children = para.children.substring(0,para.children.length-1);
        para.menu_ids = para.menu_ids.substring(0,para.menu_ids.length-1);
        $resource('/api/ac/sc/roleService/setMenuForRole', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                menuThree.exist = res.data.exist;
                menuThree.children = res.data.roleMenuList;
                menuThree.change = true;
            } else {
                alert(res.errmsg);
            }
        });
    }

    //关闭
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };

    //选择权限类型
    $scope.choose = function (menuThree,item) {
        if(!item.contain){
            item.contain = false;
        }
        var para = {'role_id': auth.id, 'id': item.id, 'contain':item.contain, 'type': '4'};
        $resource('/api/ac/sc/roleService/setMenuForRole', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                item.contain = !item.contain;
                item.change = true;
                menuThree.change = true;
            } else {
                alert(res.errmsg);
            }
        });
        
    };

};